/**
 * @description 自定义路由拦截
 */

function getAuthorization() {
  return uni.getStorageSync("token");
}
// 白名单
const whiteList = [
  "/", // 注意入口页必须直接写 '/'
  { pattern: /^\/pages\/match.*/ },
  "/pages/user/user",
  "/pages/index/index",
  { pattern: /^\/pages\/login\/*/ },
];

export default async function () {
  const list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];

  list.forEach((item) => {
    uni.addInterceptor(item, {
      invoke(e) {
        console.log("跳转");
        const url = e.url.split("?")[0];
        console.log(url);
        let pass;
        if (whiteList) {
          pass = whiteList.some((item) => {
            if (typeof item === "object" && item.pattern) {
              console.log(item);

              return item.pattern.test(url);
            }
            return url === item;
          });
        }

        // 不是白名单并且没有token
        if (!pass && !getAuthorization()) {
          // #ifdef H5 || MP-WEIXIN
          uni.navigateTo({
            url: "/pages/login/login",
          });
          // #endif
          return false;
        }
        return e;
      },
      fail(err) {
        // 失败回调拦截
        console.log(err);
      },
    });
  });
}
